const http = require('http');
const https = require('https');
const fs = require('fs');
const url = require('url');

// 声明常量
const KNOWLEDGE_ID = '1839863537204371456';
const TOKEN = '';
const PORT = 5500;
const API_HOSTNAME = 'open.bigmodel.cn';
const API_PATH = '/api/paas/v4/chat/completions';

// 输入解析函数
function parseInput(message) {
    return JSON.stringify({
        model: 'glm-4-long',
        stream: true,
        temperature: 0.5,
        top_p: 0.5,
        tools: [{ type: "retrieval", retrieval: { knowledge_id: KNOWLEDGE_ID } }],
        messages: [
            { role: "system", content: "你叫某某，是情感分析的专家，能够帮助有情感问题的人员，擅长分析情感的问题，回答问题生动形象且认真仔细。" },
            { role: "user", content: message }
        ]
    });
}

// 创建HTTP服务器
const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);
    const path = parsedUrl.pathname;

    if (path === '/send' && req.method === 'POST') {
        let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });
        req.on('end', () => {
            try {
                const { message } = JSON.parse(body);
                if (!message) {
                    res.writeHead(400, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify({ error: 'Message is required' }));
                    return;
                }
                res.writeHead(200, { 'Content-Type': 'text/event-stream' });

                const options = {
                    hostname: API_HOSTNAME,
                    path: API_PATH,
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${TOKEN}`
                    }
                };

                const apiReq = https.request(options, apiRes => {
                    apiRes.on('data', chunk => {
                        const data = chunk.toString().replace('data:', '').trim();
                        try {
                            const json = JSON.parse(data);
                            if (json.choices && json.choices[0] && json.choices[0].delta && json.choices[0].delta.content) {
                                res.write(json.choices[0].delta.content);
                            }
                        } catch (error) {
                            // Ignore JSON parsing errors
                        }
                    });
                    apiRes.on('end', () => {
                        res.end();
                    });
                });

                apiReq.on('error', error => {
                    console.error('API request failed:', error);
                    res.writeHead(500, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify({ error: 'Internal Server Error' }));
                });

                apiReq.write(parseInput(message));
                apiReq.end();
            } catch (error) {
                res.writeHead(400, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({ error: 'Invalid JSON' }));
            }
        });
    } else if (path === '/') {
        fs.readFile('index.html', (err, data) => {
            if (err) {
                res.writeHead(500, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({ error: 'Internal Server Error' }));
            } else {
                res.writeHead(200, { 'Content-Type': 'text/html' });
                res.end(data);
            }
        });
    } else {
        res.writeHead(404, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: 'Not Found' }));
    }
});

// 启动服务器
server.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});